<template>
  <div class="yzh-basic">
    <div class="flex justify-between pb-5">
      <TitleName
        title="产品记录"
        icon="i-carbon-bookmark-filled"
        class="title"
      ></TitleName
      ><!-- 
        :iconStyle="{ color: '#000' }" -->
      <div>
        产品记录数：<span class="text-blue-500"
          >{{ countCrudData.total }}条</span
        >
        产品总数：<span class="text-blue-500">{{ countCrudData.num }}</span
        >个 产品总售价：<span class="text-blue-500"
          >{{ countCrudData.totalActualPrice }}元</span
        >
        <!-- 整单折扣：<span class="text-blue-500"
          >{{ countCrudData.discount }}%</span
        > -->
        产品总金额：
        <span class="text-blue-500">{{ countCrudData.totalPrice }}元</span>
      </div>
    </div>
    <el-table :data="formData" stripe>
      <el-table-column prop="name" label="产品名称" width="150">
      </el-table-column>
      <el-table-column prop="number" label="产品编号" width="150">
      </el-table-column>
      <el-table-column prop="specification" label="规格型号" width="80">
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="80">
        <template #default="scope">
          <dict-drop
            :options="measurement_unit"
            :value="scope.row.unit"
            :isDrop="false"
        /></template>
      </el-table-column>
      <!-- <el-table-column prop="inventory" label="库存量" width="80">
      </el-table-column> -->
      <el-table-column prop="warehouseName" label="仓库" width="80">
      </el-table-column>
      <el-table-column prop="num" label="采购数量" width="80">
      </el-table-column>
      <el-table-column prop="price" label="采购单价(元)" width="120">
      </el-table-column>
      <el-table-column prop="haveStored" label="已入库数量" width="100">
      </el-table-column>
      <el-table-column prop="taxPrice" label="税额(元)" width="100">
      </el-table-column>
      <el-table-column prop="taxRate" label="税率(%)" width="80">
      </el-table-column>
      <el-table-column prop="valorem" label="价税合计(元)" width="100">
      </el-table-column>
      <el-table-column prop="totalPrice" label="采购总价(元)" width="100">
      </el-table-column>
      <el-table-column prop="present" label="赠品" width="150">
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="150">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="90"
        v-if="showTool"
      >
        <template #default="scope">
          <el-button
            plain
            type="primary"
            @click="warehousing(scope.row)"
            :disabled="scope.row.num === scope.row.haveStored"
            >入库</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="入库登记"
      v-model="visible"
      width="50%"
      :close-on-click-modal="false"
      class="receipt"
      :before-close="closeEvent"
    >
      <el-form ref="warehousingForm" :model="inputData" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称">
              <el-input disabled v-model="rowData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input disabled v-model="rowData.number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input disabled v-model="rowData.specification"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库">
              <el-input disabled v-model="rowData.warehouseName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购数量">
              <el-input disabled v-model="rowData.num">
                <template #append>{{
                  measurement_unit[rowData.unit].label
                }}</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已入库数量">
              <el-input disabled v-model="rowData.haveStored">
                <template #append>{{
                  measurement_unit[rowData.unit].label
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购单价">
              <el-input disabled v-model="rowData.price"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购备注">
              <el-input disabled v-model="rowData.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库数量" prop="num">
              <el-input
                placeholder="请输入一个有效数值"
                v-model="inputData.num"
                @input="val => changeQuantity(val)"
                @blur="blurAmount"
                ><template #append>{{
                  measurement_unit[rowData.unit].label
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                v-model="inputData.supplierId"
                placeholder="请输入供应商名称选择供应商"
                class="w-full"
                suffix-icon="Search"
                remote-show-suffix
                :suffix-transition="false"
                filterable
                remote
                :remote-method="val => querySupplier(val)"
                :loading="loadingSelect"
                no-data-text="未查询到供应商"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.id"
                  :label="item.supplierName"
                  :value="item.id"
                >
                  <div>
                    <span>{{ item.supplierName }}</span>
                    <span v-if="item.supplierNumber"
                      >({{ item.supplierNumber }})</span
                    >
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库备注">
              <el-input
                v-model="inputData.remark"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库类型">
              <el-select
                class="w-full"
                v-model="inputData.inboundType"
                disabled
                placeholder="请选择入库类型"
              >
                <el-option
                  v-for="item in inbound_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="登记人：">
              {{ useUserStore().user.nickName }}</el-form-item
            ></el-col
          >
          <el-col :span="12">
            <el-form-item label="登记时间："> {{ time }} </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="resetReceipt">重置</el-button>
        <el-button type="primary" @click="saveReceipt">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="OrderProduct">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import {
  measurement_unit //产品单位
} from '@/hooks/dict/order'
import {
  getPurProductCount,
  getPurProductList,
  inbound
} from '@/api/indentManage/indent'
import { listBySupplierrName } from '@/api/sourceModules/supplier'
import { format } from 'date-fns'
const router = useRouter()
const route = useRoute()
const props = defineProps({
  orderId: {
    type: [Number, String],
    require: true
  },
  status: {
    type: String,
    require: true
  },
  approvalStatus: {
    type: String,
    require: true
  }
})
const { proxy } = getCurrentInstance()
const { inbound_type } = proxy.useDict('inbound_type')
const commonStore = useCommonStore()
const userStore = useUserStore()
const sortOptions = ref([])
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})
const data = reactive({
  formData: [],
  countCrudData: {
    num: '-', //产品总数量
    total: '-', //产品记录数量
    totalActualPrice: '-', //产品总实际金额
    discount: '-', //整单折扣
    totalPrice: '-' //产品总金额
  },
  total: 0,
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    num: [{ message: '请输入入库数量', required: true, trigger: 'blur' }],
    supplierId: [{ message: '请输入供应商', required: false, trigger: 'blur' }]
  },
  inputData: {
    num: null,
    supplierId: null,
    remark: null,
    type: '1'
  }
})
let { formData, countCrudData, total, queryParams, inputData, rules } =
  toRefs(data)

const showTool = ref(true) //是否显示操作栏
watchEffect(() => {
  if (props.orderId) {
    console.log('porps', props)
    getFormData(props.orderId)
    if (props.status == '4' || props.approvalStatus !== '审批通过') {
      showTool.value = false
    }
  }
})
// 获取表单信息
function getFormData(id) {
  getPurProductCount(id).then(async res => {
    let resData = {}
    resData = res.data
    countCrudData.value = resData
    // console.log('countCrudData.value==>', countCrudData.value)
  })
  getList()
}
function getList() {
  let query = {
    ...queryParams.value,
    orderId: props.orderId
  }
  getPurProductList(query).then(async res => {
    let resData = {}
    resData = res.rows
    formData.value = resData
    // console.log('formData.value==>', formData.value)
  })
}

const visible = ref(false)
const rowData = ref(null)
const time = ref(null)

function warehousing(row) {
  visible.value = true
  rowData.value = row
  console.log(row)
  time.value = format(new Date(new Date().getTime()), 'yyyy-MM-dd HH:mm')
}

function changeQuantity(val) {
  if (val) {
    inputData.value.num = val
      .replace(/[^\d.]/g, '') // 限制非数字输入
      .replace(/\./g, '') // 去除小数点
  }
}

// 矫正输入金额
function blurAmount(type) {
  if (inputData.value.num) {
    inputData.value.num = inputData.value.num
      .replace(/^(\d+)\.$/g, '$1')
      .replace(/^(\d+)\.[0]+$/, '$1')
    inputData.value.num = parseFloat(inputData.value.num)
    // inputData.value.num = inputData.value.num + '' // 变回为字符串
  }
}

function closeEvent(done) {
  resetReceipt()
  done()
}

function resetReceipt() {
  inputData.value = {}
}

async function saveReceipt() {
  proxy.$refs.warehousingForm.validate(async valid => {
    if (valid) {
      if (!inputData.value.num || isNaN(inputData.value.num)) {
        proxy.$modal.msgError('请输入一个有效数值')
        return
      }

      const sum = Number(inputData.value.num) + Number(rowData.value.haveStored)
      console.log(
        `入库数量+已入库数量: ${sum} -- 采购数量:${rowData.value.num}`
      )
      if (sum > rowData.value.num) {
        proxy.$modal.msgError('当前入库数量+已入库数量超过采购数量，请重新输入')
        return
      }
      proxy
        .$confirm(
          `当前输入的入库数量为<span style='color:red'>${inputData.value.num}</span>,请确认无误`,
          '入库数量确认',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }
        )
        .then(async () => {
          inputData.value.num = Number(inputData.value.num)
          inputData.value.orderId = rowData.value.orderId
          inputData.value.productId = rowData.value.productId
          inputData.value.purchaseProductId = rowData.value.id
          const filter = supplierOptions.value.filter(v => {
            return v.id === inputData.value.supplierId
          })[0]
          if (filter) {
            inputData.value.supplierName = filter.supplierName
              ? filter.supplierName
              : ''
          } else {
            inputData.value.supplierName = ''
          }
          const res = await inbound({ ...inputData.value })
          if (res.code === 200) {
            proxy.$modal.msgSuccess('登记成功')
            resetReceipt()
            visible.value = false
            getList()
          }
        })
    }
  })
}

// 下拉loading
const loadingSelect = ref(false)
const supplierOptions = ref([]) //供应商数据
/**
 * 供应商模糊搜索
 * @param val 当前输入的值
 */
async function querySupplier(val) {
  if (!val) {
    return
  }
  let params = {
    pageSize: 10,
    supplierName: val
  }
  loadingSelect.value = true
  await listBySupplierrName(params).then(res => {
    supplierOptions.value = res.data
    loadingSelect.value = false
    console.log(supplierOptions.value, 'supplierOptions.value ')
  })
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: 600;
}

:deep(.receipt .el-form-item__label) {
  width: 100px;
}
</style>
